package com.likou;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class q51 {

    List<List<String>> ans = new ArrayList<>();
    List<String> list = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        boolean[][] visited = new boolean[n][n];

        DFS(n, 0, visited);

        return ans;
    }

    private void DFS(int n, int hang, boolean[][] visited) {
        if (hang == n) {
            ans.add(new ArrayList<>(list));
            return;
        }

        for (int i = 0; i < n; i++) {
            if (hang == 0) {
                String s = create(n, i);
                list.add(s);
                visited[hang][i] = true;
                DFS(n, hang + 1, visited);
                list.remove(list.size() - 1);
                visited[hang][i] = false;
            } else {
                if (isOK(n, hang, i, visited)) {
                    String s = create(n, i);
                    list.add(s);
                    visited[hang][i] = true;
                    DFS(n, hang + 1, visited);
                    list.remove(list.size() - 1);
                    visited[hang][i] = false;
                }
            }

        }
    }

    private boolean isOK(int n, int hang, int lie, boolean[][] visited) {
        for (int i = 0; i < hang; i++) {
            // 判断同列
            if (visited[i][lie]) {
                return false;
            }
            // 判断斜线
            if (lie - (hang - i) >= 0 && visited[i][lie - (hang - i)]) {
                return false;
            }
            if (lie + (hang - i) <= (n - 1) && visited[i][lie + (hang - i)]) {
                return false;
            }
        }
        return true;
    }

    private String create(int n, int lie) {
        // 优化
        StringBuilder s = new StringBuilder();
        char[] chars = new char[n];
        Arrays.fill(chars, '.');
        s.append(chars);
        System.out.printf(String.valueOf(s));
        s.setCharAt(lie, 'Q');

//        int i = 0;
//        for (; i < lie; i++) {
//            s.append(".");
//        }
//        s.append("Q");
//        i++;
//        for (; i < n; i++) {
//            s.append(".");
//        }

        return String.valueOf(s);
    }
}
